package com.wmx.zookerper;

import org.apache.poi.hssf.record.DVALRecord;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class ConsumerZookerper implements Watcher {
    static ZooKeeper zooKeeper = null;
    private static CountDownLatch latch =  new CountDownLatch(1);
    private final static String path = "/runoob1";
    static Stat stat = new Stat();

    public static void main(String[] args) {
        try {
            zooKeeper = new ZooKeeper("192.168.199.128:2181,192.168.199.129:2181,192.168.199.130:2181", 4000, new ConsumerZookerper());
            latch.await();
            zooKeeper.exists(path,true);
            while(true){
                Thread.sleep(Integer.MAX_VALUE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if(Event.KeeperState.SyncConnected == watchedEvent.getState()){
            if(Event.EventType.None == watchedEvent.getType() && watchedEvent.getPath() == null){
                latch.countDown();
            }else if(watchedEvent.getType()  == Event.EventType.NodeDataChanged){
                //Clinet需要去拉取最新的数据信息
                try {
                    byte[] newByte = zooKeeper.getData(watchedEvent.getPath(),true,stat);
                    System.out.println("path:"+watchedEvent.getPath()+"\tdata has changed.\t new Data :"+ new String(newByte));
                }  catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
